package com.cskaoyan.service;

import com.cskaoyan.bean.baseresultVO.BaseData;
import com.cskaoyan.bean.domain.Address;
import com.cskaoyan.bean.domain.AddressExample;
import com.cskaoyan.exception.QuaryDeletedDataException;
import com.cskaoyan.mapper.AddressMapper;
import com.github.pagehelper.PageHelper;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @User: Yr
 * @Date: 2021/12/2 15:44
 * @Description: 小程序商城-地址管理模块-service层实现类
 */

@Service
public class AddressServiceImpl implements AddressService {

    @Autowired
    AddressMapper addressMapper;


    /**
     * 获取当前账户下的全部地址信息
     *
     * @Description: 仅显示deleted为false的地址
     */
    @Override
    public BaseData list(Integer userId) {
        //获取地址数据
        AddressExample example = new AddressExample();
        example.createCriteria().andUserIdEqualTo(userId).andDeletedEqualTo(false);
        Integer count = Math.toIntExact(addressMapper.countByExample(example));
        List<Address> addressList = addressMapper.selectByExample(example);
        //返回数据
        BaseData data = BaseData.getBack(count, 1, 1, count, addressList);
        return data;
    }

    /**
     * 获取指定的地址信息
     */
    @SneakyThrows
    @Override
    public Address detail(Integer id) {
        Address address = addressMapper.selectByPrimaryKey(id);
        //if (address.getDeleted()) throw new QuaryDeletedDataException();
        return address;
    }

    /**
     * 新增/更新地址数据
     */
    @Override
    public int save(Address address) {
        if (address.getIsDefault()) {
            //是默认地址则取消其他默认地址
            Address record = new Address();
            record.setIsDefault(false);
            AddressExample example = new AddressExample();
            example.createCriteria().andIsDefaultEqualTo(true).andUserIdEqualTo(address.getUserId());
            addressMapper.updateByExampleSelective(record, example);
        }
        if (address.getId() == 0) {
            //传入id为0则新增数据
            address.setId(null);
            address.setAddTime(new Date());
            address.setUpdateTime(new Date());
            address.setDeleted(false);
            addressMapper.insert(address);
        } else {
            //不为0则更新数据
            address.setUpdateTime(new Date());
            AddressExample example = new AddressExample();
            example.createCriteria().andIdEqualTo(address.getId());
            addressMapper.updateByExampleSelective(address, example);
        }

        return address.getId();
    }


    /**
     * 删除地址信息 逻辑删除
     */
    @Override
    public int delete(Address address) {
        address.setDeleted(true);
        return addressMapper.updateByPrimaryKeySelective(address);
    }
}
